<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公司名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入公司名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公司状态" prop="isCheck">
        <el-select v-model="queryParams.isCheck" placeholder="请选择公司状态" clearable>
          <el-option
            v-for="dict in sys_check_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="联系人" prop="companyContacts">
        <el-input
          v-model="queryParams.companyContacts"
          placeholder="请输入主要联系人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人电话" prop="companyPhone" label-width="85px">
        <el-input
          v-model="queryParams.companyPhone"
          placeholder="请输入主要联系人电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['bl:company:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bl:company:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bl:company:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="false"
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['bl:company:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="blCompanyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="公司ID" align="center" prop="companyId" v-if="false"/>
      <el-table-column label="公司名称" align="center" prop="companyName" />
      <el-table-column label="公司描述" align="center" prop="companyDesc" />
      <el-table-column label="公司状态" align="center" prop="isCheck">
        <template #default="scope">
          <dict-tag :options="sys_check_status" :value="scope.row.isCheck"/>
        </template>
      </el-table-column>
      <el-table-column label="公司主要联系人" align="center" prop="companyContacts" />
      <el-table-column label="公司主要联系人电话" align="center" prop="companyPhone" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['bl:company:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['bl:company:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改下游公司对话框 -->
    <el-dialog :title="title" v-model="open" width="550px" append-to-body>
      <el-form ref="BlCompanyRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="公司状态" prop="isCheck">
          <el-select v-model="form.isCheck" placeholder="请选择公司状态">
            <el-option
              v-for="dict in sys_check_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="companyContacts">
          <el-input v-model="form.companyContacts" placeholder="请输入主要联系人" />
        </el-form-item>
        <el-form-item label="联系人电话" prop="companyPhone" label-width="95px">
          <el-input v-model="form.companyPhone" placeholder="请输入主要联系人电话" />
        </el-form-item>
      <el-form-item label="公司描述" prop="companyDesc">
         <el-input v-model="form.companyDesc" type="textarea" placeholder="请输入公司描述" />
      </el-form-item>
      <el-form-item label="经纬度" prop="lonlat">
          <el-input v-model="form.lonlat" placeholder="请通过地图选择经纬度" readonly/>
        </el-form-item>
        <input
          v-model="keyword"
          id="keyword"
          class="keyword"
          placeholder="请输入需要搜索的位置,使用鼠标点击选择经纬度"
          autocomplete="off"
          v-show = "false"
        />
        <div id="container"  v-show = "false">
          
          <!-- <el-button type="warning" style="margin-left: 15px;" @click="handleSearch">搜索</el-button>        --> 
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="blCompany">
import { listBlCompany, getBlCompany, delBlCompany, addBlCompany, updateBlCompany } from "@/api/bl/company";
import AMapLoader from '@amap/amap-jsapi-loader';
import { shallowRef } from '@vue/reactivity'

const { proxy } = getCurrentInstance();
const { sys_check_status } = proxy.useDict('sys_check_status');

const blCompanyList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const keyword = ref("");
const map = shallowRef(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    companyName: null,
    companyDesc: null,
    isCheck: null,
    companyContacts: null,
    companyPhone: null,
  },
  rules: {
    companyName: [
      { required: true, message: "公司名称不能为空", trigger: "blur" }
    ],
    companyDesc: [
      { required: false, message: "公司描述不能为空", trigger: "blur" }
    ],
    isCheck: [
      { required: true, message: "公司状态不能为空", trigger: "change" }
    ],
    companyContacts: [
      { required: true, message: "公司主要联系人不能为空", trigger: "blur" }
    ],
    companyPhone: [
      { required: true, message: "公司主要联系人电话不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询下游公司列表 */
function getList() {
  loading.value = true;
  listBlCompany(queryParams.value).then(response => {
    blCompanyList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    companyId: null,
    companyName: null,
    companyDesc: null,
    isCheck: null,
    companyContacts: null,
    companyPhone: null,
    longitude: null,
    latitude: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("BlCompanyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.companyId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加下游公司";
  initMap();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _companyId = row.companyId || ids.value
  getBlCompany(_companyId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改下游公司";
    initMap(form.value.lonlat);
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["BlCompanyRef"].validate(valid => {
    if (valid) {
      if (form.value.companyId != null) {
        updateBlCompany(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBlCompany(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _companyIds = row.companyId || ids.value;
  proxy.$modal.confirm('是否确认删除下游公司编号为"' + _companyIds + '"的数据项？').then(function() {
    return delBlCompany(_companyIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('bl/company/export', {
    ...queryParams.value
  }, `BlCompany_${new Date().getTime()}.xlsx`)
}

/**创建地图 */
function initMap(lonlat){
    AMapLoader.load({
      key:"396a57a533be016c57b48c64dad6e11b",             // 申请好的Web端开发者Key，首次调用 load 时必填
      version:"2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins:['AMap.ToolBar', 'AMap.Scale', 'AMap.PlaceSearch', 'AMap.Geocoder'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    }).then((AMap)=>{
        map.value = new AMap.Map("container",{  //设置地图容器id
        viewMode:"3D",    //是否为3D地图模式
        zoom:20,           //初始化地图级别
        center:[108.301233,23.180652], //初始化地图中心点位置
      });
     
      // 添加插件
      AMap.plugin(['AMap.AutoComplete','AMap.PlaceSearch','AMap.ToolBar'],function(){
      var autoOptions = {
        // 城市，默认全国 
        city: "南宁",
        // 使用联想输入的input的id
        input: "keyword"
      }
      var autocomplete= new AMap.AutoComplete(autoOptions)

      var placeSearch = new AMap.PlaceSearch({
        city:'南宁',
        map:map.value
      })
      autocomplete.on('select', function(e){
        //TODO 针对选中的poi实现自己的功能
        placeSearch.search(e.poi.name)
      })

      var toolbar = new AMap.ToolBar();
      map.value.addControl(toolbar);  

    })
       if(lonlat !== null && lonlat !== undefined && lonlat !== ''){
        var arr = lonlat.split(",");
        var lon = arr[0];
        var lat = arr[1];
        var marker = new AMap.Marker({
          icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
          position: [lon,lat],
          offset: new AMap.Pixel(-13, -30)
        });
        marker.setMap(map.value);
       }
        
      map.value.on('click', function(e) { 
        // alert('您在[ '+e.lnglat.getLng()+','+e.lnglat.getLat()+' ]的位置点击了地图！'); 
        // console.log(e.lnglat.getLng()+','+e.lnglat.getLat());
        // form.longitude = e.lnglat.getLng()+','+e.lnglat.getLat();
        form.value.lonlat=e.lnglat.getLng()+','+e.lnglat.getLat();
        var marker = new AMap.Marker({
          icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
          position: [e.lnglat.getLng(),e.lnglat.getLat()],
          offset: new AMap.Pixel(-13, -30)
        });
        map.value.clearMap();
        marker.setMap(map.value);
      });

    }).catch(e=>{
      console.log(e);
    })
  }

  function handleSearch(){
    var placeSearch = new AMap.PlaceSearch({
        city:'南宁',
        map:map.value
      })
    placeSearch.search("荣和大地");
  }

  function addMarker() {
      var marker = new AMap.Marker({
        icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
        position: [116.406315, 39.908775],
        offset: new AMap.Pixel(-13, -30)
      });
      marker.setMap(map);
    }
getList();
</script>
<style scoped>
#container{
  padding:0px;
  margin: 0px;
  width: 100%;
  height: 250px;
}
.keyword{
position: absolute;  
z-index: 99999999999;
border:0;
outline:0;
width: 350px;
height: 30px;
margin-left: 30px;
border:solid 1px red;
}
</style>
